package config

import (
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"go.uber.org/zap"
)

// 全局变量 保存程序所有配置信息
var Conf = new(AppConfig)

type AppConfig struct {
	Name string `mapstructure:"name"`
	Mode string `mapstructure:"mode"`
	Port int `mapstructure:"port"`
	Version string `mapstructure:"version"`
	StartTime string `mapstructure:"start_time"`
	MachineID int64 `mapstructure:"machine_id"`
	*LogConfig `mapstructure:"log"`
	*MysqlConfig `mapstructure:"mysql"`
	*RedisConfig `mapstructure:"redis"`
}

type LogConfig struct {
	Level string `mapstructure:"level"`
	Filename string `mapstructure:"filename"`
	MaxSize int `mapstructure:"max_size"`
	MaxAge int `mapstructure:"max_age"`
	MaxBackups int `mapstructure:"max_backups"`
	Compress bool `mapstructure:"compress"`
}

type MysqlConfig struct {
	Host string `mapstructure:"host"`
	Port int `mapstructure:"port"`
	User string `mapstructure:"user"`
	Password string `mapstructure:"password"`
	DBName string `mapstructure:"db_name"`
	MaxOpenConns int `mapstructure:"max_open_conns"`
	MaxIdleConns int `mapstructure:"max_idle_conns"`
}

type RedisConfig struct {
	Host string `mapstructure:"host"`
	Port int `mapstructure:"port"`
	Password string `mapstructure:"password"`
	DB int `mapstructure:"db"`
	PoolSize int `mapstructure:"pool_size"`
}

func Init() (err error) {
	viper.AddConfigPath("./config/")	// 配置文件所在路径，可以多次调用添加多个路径来查找
	viper.SetConfigName("config")	// 配置文件名字
	viper.SetConfigType("yaml")

	err = viper.ReadInConfig()
	if err!=nil{
		zap.L().Error("read config info by viper failed ", zap.Error(err))
		return
	}
	if err=viper.Unmarshal(Conf); err!=nil{
		zap.L().Error("unmarshal config To Conf failed ", zap.Error(err))
		return
	}
	viper.WatchConfig()
	viper.OnConfigChange(func(in fsnotify.Event) {
		zap.L().Info("配置文件修改了...")
		if err:=viper.Unmarshal(Conf); err!=nil{
			zap.L().Error("unmarshal new config To Conf failed ", zap.Error(err))
			return
		}
	})
	return nil
}